import React from 'react';
import { Icon,Bubble } from 'weaver-mobile';
import { _,InputUtil,FieldUtil,FormatUtil } from '../../util/pcPublic';
import { getLabel } from '../../util/common';
const trim = _.trim;

export default class WfInput extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			value: props.value ? props.value : '',
			isonfocus: false,
			location: -1
		};
		this.inputRef = React.createRef();
	}
	componentWillReceiveProps(nextProps) {
		if(this.state.value !== nextProps.value)
			this.setState({value: nextProps.value});
	}
	componentDidUpdate(prevProps, prevState){
		if(this.state.isonfocus === true && prevState.isonfocus === false){
			let isIos = (/OS [\d._]+/gi).test(window.navigator.userAgent)
			if(!isIos){
				this.setLocation();		//state变更是异步的，需要DidUpdate时获取焦点定位光标位置
			}
		}
	}
	componentWillUnmount(){
		const { viewAttr,isDetail } = this.props;
		if(isDetail && viewAttr > 1 && this.state.isonfocus){	//未失去焦点直接返回情况
			this.doFocusEvent(false);
		}
	}
	render() {
		let { value,isonfocus } = this.state;
		let { viewAttr,fieldid,fieldMark,detailtype,qfws,format={},isDetail,emptyShowContent,showhtml } = this.props;
		if(detailtype !==1){
			value = trim(value).length > 0 ? value.replace(/\,/g,'') : '';
		}
		if(detailtype === 4)	//金额大写默认以格式化方式实现
			format = { numberType:101 };
		let formatvalue = this.transFormatValue(value, format);
		const numberType = parseInt(format.numberType)||0;
		// if(!isonfocus && numberType === 100){	//财务表览
		// 	return <WeaWfFinancial type={2} finNum={format.finaNum} className={`finarea_${fieldid}`} viewAttr={viewAttr}
		// 		value={value} clickEvent={this.doFocusEvent.bind(this,true)} />
		// }
		let style = {};
		if(numberType === 2 && (format.formatPattern == "1" || format.formatPattern == "4")){
			//格式化值负数则变为红色
			style["color"] = !isonfocus && InputUtil.judgeIsNumber(value) && parseFloat(value) < 0 ? "#FF0000" : "inherit";
		}
		const swapClassName = `wf-req-input-item wf-input-${detailtype} wf-input-field${fieldid} ${viewAttr === 1 ? "wf-input-view" : "wf-input-edit"}`;
		if(viewAttr === 1){		//只读
			if(!!showhtml)	//接口控制只读显示值
				formatvalue = showhtml;
			return (
				<div className={swapClassName}>
					<div id={`${fieldMark}span`} className="wf-input-view-box" style={style} dangerouslySetInnerHTML={{__html:formatvalue}}></div>
					<input type="hidden" id={fieldMark} name={fieldMark} value={value}/>
				</div>
			)
		}else{		//可编辑
			const inputType = isonfocus && detailtype > 1 ? "text" : "text";
			let placeholder = "";
			// //支持可编辑无值时显示灰色默认值(移动端替换placeholder实现)
			if(!isonfocus &&  formatvalue.toString() === ""){
				if(!!emptyShowContent){
					placeholder = emptyShowContent;
				}else{
					placeholder = getLabel(83869,"请输入")
				}
			}
			const isRequired = viewAttr === 3 && trim(value).length === 0;
			return(
				<div className={swapClassName}>
					<input
						ref={this.inputRef}
						id={fieldMark}
						name={fieldMark}
						type={inputType}
						className="wf-input-edit-box"
						placeholder={placeholder}
						value={isonfocus ? value : formatvalue}
						onKeyDown={this.doKeyDown.bind(this)}
						onChange={this.setInputText.bind(this)}
						onFocus={this.doFocusEvent.bind(this,true)}
						onBlur={this.doFocusEvent.bind(this,false)}
						style={style}
					/>
					{
						isRequired && <div className="wf-input-required-icon">
							<img src="/images/BacoError_wev9.png" align="absmiddle" />
						</div>
					}
					<div className="wf-input-edit-icon" onClick={this.editIconClickEvent.bind(this)}>
                        <Icon type="editor-01" />
                    </div>
				</div>
			)
		}
	}
	editIconClickEvent(){
		const { isonfocus } = this.state;
		if(!isonfocus){
			const elm = this.inputRef.current;
			elm.focus();
		}
	}
	setInputText(e) {
		const { detailtype,length,fieldlabel } = this.props;
		let value  = e.target.value;
		if(detailtype === 1) {
			let valLen = InputUtil.realLength(value);
			if(length && valLen > length) {
				Bubble.warning(`${fieldlabel}${getLabel(20246,'文本长度不能超过')}${length}(${getLabel(124962,'1个中文字符等于3个长度')})`);
				value  =  InputUtil.checkLength(value,valLen,length);
			}
		}
		this.setState({value: value});
	}
	doKeyDown(e){
		const { enableInput,onDisablePrompt } = this.props;
		if(enableInput === false) {		//禁止输入字段，输入时触发事件
			typeof(onDisablePrompt) === "function" && onDisablePrompt();
			e.preventDefault();
			return;
		}
		const keyCode = e.nativeEvent.keyCode;
		if(keyCode === 13){
			e.preventDefault();		//阻止enter键
		}
		e.stopPropagation();	//阻止冒泡
	}
	doFocusEvent(bool,e){
		const { fieldMark } = this.props;
		if(this.props.viewAttr === 1)
			return;
		if(bool){	//获取焦点
			this.setState({ isonfocus:bool, location:this.getLocation()});//
			window.WfForm && window.WfForm.triggerFieldAction("onfocus", fieldMark);
		}else{	//失去焦点
			let value = e ? this.checkLen(e.target.value) : this.state.value;	//验证长度
			let realValue = this.transRealValue(value);
			this.props.onChange && this.props.onChange(realValue);
			this.setState({isonfocus:bool, value:realValue});
			window.WfForm && window.WfForm.triggerFieldAction("onblur", fieldMark);
		}
	}
	getLocation(){
		try{ 	//计算鼠标焦点位置
			const elm = this.inputRef.current;
			if(typeof elm.selectionStart === 'number')
				return elm.selectionStart;
		}catch(e){
			return -1;
		}
	}
	setLocation(){	//设置鼠标焦点位置
		const elm = this.inputRef.current;
		const location = elm.value.length;
		// let location = this.state.location;
		// if(location <= 0 || location > elm.value.length)	//定位到最后
		// 	location = elm.value.length;
		if(elm.setSelectionRange)
			elm.selectionStart = elm.selectionEnd = location;
	}
	transRealValue(value){
		const {detailtype, qfws} = this.props;
		let realValue = value;
		if(detailtype !== 1){
			let isqfw = detailtype === 5;
			realValue = FieldUtil.convertFloatValue(value,qfws,isqfw);
		}
		return realValue;
	}
	transFormatValue(value, format){
		let { detailtype,qfws,viewAttr } = this.props;
		if(detailtype !== 1){
			value = trim(value).length > 0 ? value.replace(/\,/g,'') : '';
		}
		let formatvalue = value;
		const numberType = parseInt(format.numberType)||0;
		//失去焦点
		if(numberType > 0){
			if(numberType === 100 ){ //财务预览
			}else if(numberType === 101 ){ //财务金额大写
				formatvalue = InputUtil.convertAmountChinese(value);
			}else{
				formatvalue = FormatUtil.convertFormatValue(value, format);
			}
		}else{
			if(detailtype !==1){
				let isqfw = false;
				if(detailtype === 4 || detailtype === 5){
					isqfw = true;
				}
				formatvalue = FieldUtil.convertFloatValue(value, qfws, isqfw);
			}
		}
		//只读-金额大写字段后面跟小写数值
		if(viewAttr === 1 && detailtype === 4 && value !== "")
			formatvalue = `${formatvalue}(${FieldUtil.convertFloatValue(value, 2, true)})`;
		return formatvalue;
	}
	checkLen(val){
		let {detailtype,length,qfws,fieldlabel} = this.props;
		if(detailtype === 1) {
			let valLen = InputUtil.realLength(val);
			if(length && valLen > length) {
				Bubble.warning(`${fieldlabel}${getLabel(20246,'文本长度不能超过')}${length},(${getLabel(124962,'1个中文字符等于3个长度')})`);
				val  =  InputUtil.checkLength(val,valLen,length);
			}
			return val;
		}
		if(trim(val).length === 0 ) return "";
		if(trim(val).length === 1 && val.charCodeAt(0) === 45) return val;
		if(!InputUtil.judgeIsNumber(val))
			return "";
		if(val.charCodeAt(0) === 45) length = length + 1;
		const arr = val.toString().split(".");
		if(trim(arr[0]).length > length - qfws) {
			Bubble.warning(`${getLabel(385128,'整数位数长度不能超过')}${length-qfws}${getLabel(386375,'位，请重新输入！')}`,5);
			return "";
		}
		return val;
	}

}